<template>
	<view class="view-contain">
		<!-- 公共模块，显示返回箭头和标题 -->
		<public-module leftIcon="arrow-left" :title="title" />

		<!-- 自定义标签页切换 -->
		<view class="custom-tabs">
			<view v-for="(item, index) in tabList" :key="index"
				:class="['tab-item', currentTab === index ? 'active' : '']" @click="handleTabChange(index)">
				{{ item.name }}
			</view>
		</view>

		<mescroll-uni :height="`${height}px`" :down="downOption" :up="upOption" @init="mescrollInit"
			@down="downCallback" @up="upCallback">
			<view class="list-container">
				<view v-for="(item, index) in listData" :key="index" class="list-item" @click="goToDetail(item)">
					<view class="first-row">
						<text class="serial-number">{{index + 1}}</text>
						<text class="user-name">{{item.userNickname}}</text>
						<text class="title">{{item.paperName}}</text>
					</view>
					<view class="second-row">
						<text class="rate">得分:{{item.score}}</text>
						<text class="rate">击败:{{item.beatRate}}</text>						
						<text class="rate">点赞:{{item.likes}}</text>
						<!-- 使用格式化方法处理日期 -->
						<text class="rate">{{formatDate(item.reviewTime)}}</text>
					</view>
				</view>
			</view>
		</mescroll-uni>
		
		<!-- 新增复盘按钮 -->
		<view class="add-review-btn" @click="addReview">
			<u-icon name="plus" color="#FFFFFF" size="24"></u-icon>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import {
		examReviewList
	} from "@/config/api.js";
	export default {
		mixins: [MescrollMixin],
		data() {
			return {
				height: 0,
				currentTab: 0,
				tabList: [{
						name: '我的复盘',
						type: 'my'
					},
					{
						name: '考友最新',
						type: 'latest',
						orderBy: 'reviewTime'
					},
					{
						name: '最多收藏',
						type: 'mostCollected',
						orderBy: 'likes'
					},
					{
						name: '我的收藏',
						type: 'myCollect',
						myCollect: 1
					}
				],
				listData: [],
				downOption: {
					use: true
				},
				upOption: {
					textNoMore: '没有更多了~',
					toTop: {
						right: '24rpx',
						bottom: '60rpx'
					}
				},
				needRefresh: false
			}
		},
		computed: {
			...mapState(['user', 'loginSuccess']),
			title() {
				return '复盘打卡';
			}
		},
		onLoad() {
			const res = uni.getWindowInfo();
			this.height = res.windowHeight - 100; // 100为组件高度
		},
		methods: {
			...mapMutations([]),

			// 日期格式化方法：将精确到秒的时间转换为年月日
			formatDate(dateString) {
				if (!dateString) return '';
				
				// 创建日期对象（兼容不同格式的日期字符串）
				// iOS兼容的日期解析
				const isoString = dateString.replace(' ', 'T');
				const date = new Date(isoString);
				
				// 获取年、月、日
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
				const day = String(date.getDate()).padStart(2, '0');
				
				// 返回格式化后的日期字符串
				return `${year}-${month}-${day}`;
			},

			// 修改后的新增复盘方法
			addReview() {
				uni.navigateTo({
					url: '/pages/review/add'
				});
			},

			// 标签切换
			async handleTabChange(index) {
				if (index < 0 || index >= this.tabList.length) return;
				this.currentTab = index;
				this.listData = [];

				await this.$nextTick();
				if (this.mescroll) {
					this.mescroll.resetUpScroll(false);
				}
			},

			async upCallback(page) {
				try {
					const currentTab = this.tabList[this.currentTab];
					let params = `?pageNum=${page.num}&pageSize=${page.size}`;

					// 根据当前标签配置添加参数
					if (currentTab.orderBy) {
						params += `&orderBy=${currentTab.orderBy}`;
					}
					if (currentTab.myCollect) {
						if (!this.user.userId) {
							// 静默登录机制，直接跳转到首页
							uni.reLaunch({
								url: '/pages/index/index'
							});
							return;
						}
						params += '&myCollect=1';
					}

					const res = await examReviewList(params);
					if (res && res.rows) {
						this.mescroll.endBySize(res.rows.length, res.total);
						if (page.num == 1) this.listData = [];
						this.listData = this.listData.concat(res.rows);
					}
				} catch (error) {
					this.mescroll.endErr();
					uni.$u.toast('获取复盘列表失败');
				}
			},
			goToDetail(item) {
				const fromTab = this.tabList[this.currentTab].type;
				uni.navigateTo({
					url: `/pages/review/detail?id=${item.id}&from=${fromTab}`
				});
			}
		},
		onShow() {
			if (this.needRefresh) {
				this.needRefresh = false;
				this.mescroll && this.mescroll.resetUpScroll();
			}
		},
		created() {
			// 监听刷新事件
			uni.$on('refreshReviewList', () => {
				this.mescroll && this.mescroll.resetUpScroll();
			});
		},
		beforeDestroy() {
			// 移除事件监听
			uni.$off('refreshReviewList');
		}
	}
</script>

<style>
	.custom-tabs {
		display: flex;
		background-color: #FFFFFF;
		padding: 0 20rpx;
		border-bottom: 1px solid #eee;
	}

	.tab-item {
		position: relative;
		padding: 24rpx 32rpx;
		font-size: 28rpx;
		color: #666;
		transition: all 0.3s;
	}

	.tab-item.active {
		color: #409EFF;
		font-weight: 500;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 4rpx;
		background-color: #409EFF;
		border-radius: 2rpx;
	}
	.view-contain {
		display: flex;
		flex-direction: column;
		background-color: #F5F6F5;
		min-height: 100vh;
	}

	.list-container {
		width: 100%;
		padding: 0;
	}

	.list-item {
		padding: 24rpx;
		background-color: #FFFFFF;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.first-row {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.serial-number {
		font-size: 28rpx;
		color: #666;
		/* 序号占较小空间 */
		text-align: center;
	}

	.user-name {
		font-size: 28rpx;
		color: #333;
		margin-right: 16rpx;
		flex: 2;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		padding-left: 0.5em;
		/* 添加左内边距使文字右移 */
	}


	.title {
		font-size: 32rpx;
		flex: 3;
		/* 试卷名占较大空间 */
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.second-row {
		display: flex;
		justify-content: space-between;
	}

	.rate {
		font-size: 28rpx;
		color: #666;
		flex: 1;
		/* 分数和击败比各占一半 */
		text-align: center;
	}

	.no-data {
		padding: 100rpx 0;
	}

	/* 新增复盘按钮样式 */
	.add-review-btn {
		position: fixed;
		right: 20px;
		top: 50%; /* 垂直居中 */
		transform: translateY(-50%); /* 精确居中 */
		background-color: #007aff;
		width: 40px;
		height: 40px;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		z-index: 999; /* 确保按钮在最上层 */
	}
</style>
